import React, { useRef } from 'react';
import { ProTable, PageContainer } from '@ant-design/pro-components';
import { Button, Space, Image, Tag, Modal, message } from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  ExportOutlined,
} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import type { ProColumns, ActionType } from '@ant-design/pro-components';
import adminApi from '@/api/admin-api';

const { confirm } = Modal;

interface CardItem {
  id: number;
  word: string;
  phrase: string;
  image_url?: string;
  audio_url?: string;
  language: string;
  topic_id: number;
  topic_name?: string;
  status: string;
  created_at: string;
  updated_at: string;
}

const CardList: React.FC = () => {
  const navigate = useNavigate();
  const actionRef = useRef<ActionType>();

  // 删除处理
  const handleDelete = (id: number) => {
    confirm({
      title: '确认删除',
      content: '确定要删除这张卡片吗？此操作不可恢复。',
      okText: '确定',
      cancelText: '取消',
      onOk: async () => {
        try {
          await adminApi.cardManagement.adminCardsDelete({ id });
          message.success('删除成功');
          actionRef.current?.reload();
        } catch (error) {
          message.error('删除失败');
        }
      },
    });
  };

  // 导出处理
  const handleExport = () => {
    message.info('导出功能开发中...');
  };

  // ProTable列配置
  const columns: ProColumns<CardItem>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      width: 80,
      search: false,
    },
    {
      title: '图片',
      dataIndex: 'image_url',
      width: 100,
      search: false,
      render: (_, record) => (
        <Image
          width={60}
          height={60}
          src={record.image_url}
          style={{ borderRadius: 4 }}
          fallback=""
        />
      ),
    },
    {
      title: '单词',
      dataIndex: 'word',
      width: 120,
      ellipsis: true,
    },
    {
      title: '短语/翻译',
      dataIndex: 'phrase',
      width: 150,
      ellipsis: true,
    },
    {
      title: '语言',
      dataIndex: 'language',
      width: 80,
      valueType: 'select',
      valueEnum: {
        en: { text: '英语', status: 'Processing' },
        zh: { text: '中文', status: 'Success' },
      },
      render: (_, record) => (
        <Tag color={record.language === 'en' ? 'blue' : 'green'}>
          {record.language === 'en' ? '英语' : '中文'}
        </Tag>
      ),
    },
    {
      title: '主题',
      dataIndex: 'topic_name',
      width: 120,
      search: false,
      render: (_, record) => (
        <Tag color="purple">
          {record.topic_name || '未分类'}
        </Tag>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 80,
      valueType: 'select',
      valueEnum: {
        active: { text: '启用', status: 'Success' },
        inactive: { text: '禁用', status: 'Default' },
      },
      render: (_, record) => (
        <Tag color={record.status === 'active' ? 'success' : 'default'}>
          {record.status === 'active' ? '启用' : '禁用'}
        </Tag>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      width: 180,
      valueType: 'dateTime',
      search: false,
    },
    {
      title: '操作',
      valueType: 'option',
      width: 150,
      render: (_, record) => [
        <Button
          key="edit"
          type="link"
          size="small"
          icon={<EditOutlined />}
          onClick={() => navigate(`/cards/edit/${record.id}`)}
        >
          编辑
        </Button>,
        <Button
          key="delete"
          type="link"
          size="small"
          danger
          icon={<DeleteOutlined />}
          onClick={() => handleDelete(record.id)}
        >
          删除
        </Button>,
      ],
    },
  ];

  return (
    <PageContainer
      header={{
        title: '卡片管理',
        breadcrumb: {
          items: [
            { title: '首页' },
            { title: '卡片管理' },
            { title: '卡片列表' },
          ],
        },
      }}
    >
      <ProTable<CardItem>
        columns={columns}
        actionRef={actionRef}
        cardBordered
        request={async (params, sort, filter) => {
          try {
            const response = await adminApi.cardManagement.adminCards({
              page: params.current || 1,
              page_size: params.pageSize || 10,
              keyword: params.word,
              language: params.language,
              status: params.status,
            });

            return {
              data: response.data.list || [],
              success: true,
              total: response.data.total || 0,
            };
          } catch (error) {
            return {
              data: [],
              success: false,
              total: 0,
            };
          }
        }}
        editable={{
          type: 'multiple',
        }}
        columnsState={{
          persistenceKey: 'pro-table-card-list',
          persistenceType: 'localStorage',
        }}
        rowKey="id"
        search={{
          labelWidth: 'auto',
          defaultCollapsed: false,
        }}
        options={{
          setting: {
            listsHeight: 400,
          },
        }}
        form={{
          syncToUrl: (values, type) => {
            if (type === 'get') {
              return {
                ...values,
                created_at: [values.startTime, values.endTime],
              };
            }
            return values;
          },
        }}
        pagination={{
          pageSize: 10,
          showQuickJumper: true,
          showSizeChanger: true,
        }}
        dateFormatter="string"
        headerTitle="卡片列表"
        toolBarRender={() => [
          <Button
            key="button"
            icon={<PlusOutlined />}
            onClick={() => navigate('/cards/create')}
            type="primary"
          >
            新建卡片
          </Button>,
          <Button
            key="export"
            icon={<ExportOutlined />}
            onClick={handleExport}
          >
            导出
          </Button>,
        ]}
      />
    </PageContainer>
  );
};

export default CardList;